package com.blog.util;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate4辅助类
 * @author Administrator
 *
 */
 
public final class HibernateUtil {
	static Logger log = Logger.getLogger(HibernateUtil.class);
	/**
	 * 线程安全的全局对象
	 * 创建并打开Session
	 */
	private static SessionFactory sessionFactory;
	/**
	 * 静态块，优先于无参构造函数
	 */
	static{
		// sessionF();
	 
	}
	
 
	 
	 
	static final void sessionF(){
		/*
		 * sessionFactory = new Configuration().configure().buildSessionFactory(); 
		 * 这是hibernate3的用法，hibernate4已改变。
		 * */
		Configuration cfg = new Configuration();
		 cfg.configure("hibernate.cfg.xml");
		try {
			 
			ServiceRegistry serviceR=null;
			 serviceR = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
				sessionFactory = cfg.buildSessionFactory(serviceR);
		} catch (HibernateException e) {
			log.error("SessionFactory初始化出現錯誤。");;
			e.printStackTrace();
		} 
	}
	public static SessionFactory getSessionfactory() {
		log.info("获取sessionFactory.");
		if(sessionFactory!=null){
			return sessionFactory;
		}
		sessionF();
		return sessionFactory;
	}
	
	
}
